package com.sasken.pdb.models.settings
{
	import mx.collections.ArrayCollection;
	import mx.collections.IList;
	
	/**
	 *  A collection of public static functions for managing lists and finding items from them.
	 */ 
	public class ListUtil
	{
		/**
		 *  Returned when item was not found from the list in a search.
		 */ 
		public static var NOT_FOUND:int = -1;
		
		/** 
		 *  Find an item index from a list. Returns 0 if not found.
		 */ 
		public static function findListIndex(array:IList, value:Object):int
		{
			for(var i:int = 0; i < array.length; ++i)
			{
				if (array.getItemAt(i) == value)
				{
					return i;
				}
			}	
			return NOT_FOUND;
		}
		
		/**
		 *  Finds an item by its attribute. 
		 *  @param array The list to search for.
		 *  @param label The property in the object to search.
		 *  @param value The value of the property to find.
		 */ 
		public static function findByAttribute(array:IList, label:String, value:*):int
		{
			for(var i:int = 0; i < array.length; ++i)
			{
				var obj:Object = array.getItemAt(i);
				
				// this code doesn't work so well unless property is public var. getters/setters don't work?
				var cmpStr:String = obj[label] ? obj[label].toString() : null;
				if (cmpStr == value)
				{
					return i;
				}
			}	
			return NOT_FOUND;
		}
		
		/**
		 *  Tests if lists equal to each other. Works only if items are same references. 
		 *  For other uses, use ObjectUtil.compare() for example.
		 *  @param list1 The first list to compare.
		 *  @param list2 The second list to compare.
		 *  @return True if lists equal to each other.
		 */ 
		public static function listsEqual(list1:IList, list2:IList):Boolean
		{
			if (list1.length != list2.length) return false;
			
			for (var i:int = 0; i < list1.length; ++i)
			{
				if (list1.getItemAt(i) != list2.getItemAt(i))
				{
					return false;	
				}	
			}
			
			return true;
		}
		
		/**
		 *  Tests if arrays equal to each other. Works only if items are same references. 
		 *  For other uses, use ObjectUtil.compare() for example.
		 *  @param list1 The first array to compare.
		 *  @param list2 The second array to compare.
		 *  @return True if arrays equal to each other.
		 */ 
		public static function arraysEqual(list1:Array, list2:Array):Boolean
		{
			if (list1.length != list2.length) return false;
			
			for (var i:int = 0; i < list1.length; ++i)
			{
				if (list1[i] != list2[i])
				{
					return false;	
				}	
			}
			
			return true;
		}
		
		public static function copyArrayCollection(src1:ArrayCollection):ArrayCollection
		{
			var dest:ArrayCollection = new ArrayCollection();
			if(src1 != null && src1.length > 0)
			{
				for(var i:int = 0; i < src1.length; i++)
				{
					dest.addItem(src1.getItemAt(i));
				}
			}
			
			return dest;
		}

	}
}